<!--
/**
* @author xuyh0817
* @email xuyh0817@foxmail.com
* @date 2022-03-27 22:56
* @version 2.0.0
* @doc todo
* @website todo
* @remark  如果要分发源码，需在本文件顶部保留此文件头信息！！
*/
-->
<template>
  <a-modal
    title="批量添加列项"
    :visible="visible"
    :footer="null"
    centered
    :mask-closable="false"
    destroy-on-close
    width="50%"
    @cancel="$emit('update:visible',false)"
  >
    <div class="x-render-code">
      <a-radio-group v-model="addType" style="margin-bottom: 20px;">
        <a-radio value="item">逐个添加</a-radio>
        <a-radio value="db">数据库文件导入[MYSQL]</a-radio>
        <!--        <a-radio value="remote">远程导入[GET]</a-radio>-->
      </a-radio-group>

      <a-row v-for="(item,index) in columnOption" :key="index" :gutter="[8,8]">
        <a-col span="8">
          <div
            style="width: 100%;padding: 2px;"
            :class="fieldCountObj[item.dataIndex] > 1 || !item.dataIndex ? 'form-item-error':'' "
          >
            <a-input
              :value="item.dataIndex"
              placeholder="请输入dataIndex"
              allow-clear
              type="text"
              @change="changeHandler($event,index,'dataIndex')"
            />
          </div>
        </a-col>
        <a-col span="8">
          <a-input
            :value="item.title"
            placeholder="请输入title"
            allow-clear
            type="text"
            @change="changeHandler($event,index,'title')"
          />
        </a-col>
        <a-col span="8">
          <div style="display: flex;flex-flow: row nowrap;">
            <a-input-number
              :step="1"
              :max="999"
              :min="1"
              :value="item.width"
              @change="changeHandler($event,index,'width')"
            />
            <div class="x-render-icon-container">
              <a-icon
                v-if="columnOption.length !== 1"
                :style="{ fontSize: '24px' }"
                type="minus-circle"
                @click="removeHandler(index)"
              />
              <a-icon
                v-if="columnOption.length - 1 === index"
                :style="{ fontSize: '24px' }"
                type="plus-circle"
                @click="addHandler"
              />
            </div>
          </div>
        </a-col>
      </a-row>
      <div v-show="addType === 'db'">
        <a-textarea v-model="sql" allow-clear placeholder="请输入数据结构" :rows="4"/>
      </div>

      <div v-show="addType === 'remote'">
        <a-textarea v-model="remoteUrl" allow-clear placeholder="请输入远程地址" :rows="4"/>
      </div>

      <a-row :gutter="[20,10]">
        <a-col span="24">
          <p style="color: #f44;line-height: 24px;" v-html="errorTip"/>
        </a-col>
        <a-col span="24" style="text-align: center;">
          <a-button v-show="addType === 'db'" type="primary" style="margin: 0 8px;" @click="mysqlImportHandler">导入
          </a-button>
          <a-button v-show="addType === 'remote'" type="primary" style="margin: 0 8px;" @click="remoteImportHandler">
            导入
          </a-button>
          <a-button type="primary" @click="addFormItemHandler">提交</a-button>
        </a-col>
      </a-row>
    </div>
  </a-modal>
</template>

<script>
import { assign, cloneDeep, countBy } from 'lodash'

export default {
  name: 'XRenderBatchDialog',
  inject: ['xDesignTable'],
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      sql: '',
      addType: 'item',
      remoteUrl: '',
      columnOption: []
    }
  },
  computed: {
    // 字段出现的次数
    fieldCountObj: {
      get() {
        const { xDesignTable, columnOption } = this
        const columnOptionsCount = countBy(xDesignTable.tableColumnOptions, ({ dataIndex }) => String(dataIndex).trim())
        const columnCount = countBy(columnOption, ({ dataIndex }) => String(dataIndex).trim())
        const assignObj = assign({}, columnOptionsCount, columnCount)
        for (const key of Object.keys(assignObj)) {
          assignObj[key] = (columnOptionsCount[key] ? columnOptionsCount[key] : 0) + (columnCount[key] ? columnCount[key] : 0)
        }
        return assignObj
      }
    },
    errorTip: {
      get() {
        const { fieldCountObj: countObj } = this
        let emptyKey = false
        const countMessage = []
        for (const key of Object.keys(countObj)) {
          if (!key) {
            emptyKey = true
          }
          if (!!key && countObj[key] > 1) {
            countMessage.push(key)
          }
        }
        let message = ''
        if (emptyKey) {
          message = 'dataIndex存在空值,请填写！<br/>'
        }
        if (countMessage.length > 0) {
          message += '属性存在多个：' + countMessage.join(',')
        }

        return message ? '注意: <br/>' + message : message
      }
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        if (val) {
          const { columnOption } = this
          columnOption.splice(0, columnOption.length, {
            title: '序号',
            dataIndex: 'index',
            width: 100
          })
        }
      }
    }
  },
  methods: {
    mysqlImportHandler() {
    },
    remoteImportHandler() {
      const { remoteUrl } = this
      if (!remoteUrl) {
        this.$message.error('地址不能为空')
        return
      }
    },
    addColumns(data) {
      const keys = Object.keys(data)
      if (keys.length === 0 || typeof (data) !== 'object') {
        return
      }
      const { xDesignTable } = this
      for (const key of keys) {
        if (typeof (data[key]) !== 'object') {
          this.$set(xDesignTable.dataSource[0], key, data[key])
          this.addFormItem(key)
        }
        this.addColumns(data[key])
      }
    },
    addFormItemHandler() {
      if (this.errorTip) {
        this.$message.error('请修改错误内容')
        return
      }
      const { xDesignTable, columnOption } = this
      for (const option of columnOption) {
        let flag = false
        for (const tableColumn of xDesignTable.tableColumnOptions) {
          if (option.dataIndex === tableColumn.dataIndex && !!option.dataIndex) {
            flag = true
            break
          }
        }
        if (!flag) {
          if (!xDesignTable.dataSource[0][option.dataIndex]) {
            this.$set(xDesignTable.dataSource[0], option.dataIndex, Date.now())
          }
          xDesignTable.tableColumnOptions.splice(xDesignTable.tableColumnOptions.length, 0, cloneDeep(option))
        }
      }
      this.$message.success('添加成功')
      this.$emit('update:visible', false)
    },
    addHandler() {
      this.addFormItem()
    },
    addFormItem(dataIndex = Date.now() + '', title = '') {
      this.columnOption.push(
        {
          title,
          dataIndex,
          width: 100
        }
      )
    },
    removeHandler(index) {
      this.columnOption.splice(index, 1)
    },
    changeHandler(event, index, prop) {
      const value = event.target.value
      this.$set(this.columnOption[index], prop, value)
    }
  }
}
</script>
<style lang="css" scoped>
.x-render-code {
  width: 100%;
  max-height: calc(80vh - 50px);
  overflow-y: auto;
  overflow-x: hidden;
}

.x-render-icon-container {
  width: 20%;
  padding: 0 5px;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-content: center;
  align-items: center;
}

.form-item-error {
  border: 1px #f44 dashed;
  border-radius: 5px;
}
</style>
